var cf = require("../../../config.js");
var util = require("../../../utils/util.js");
var cusmallToken = wx.getStorageSync('cusmallToken');
var baseHandle = require("../../template/baseHandle.js");
//获取应用实例
var app = getApp();
Page(Object.assign({}, baseHandle, {

  /**
   * 页面的初始数据
   */
  data: {
    extConfig: wx.getExtConfigSync ? wx.getExtConfigSync() : {},
    app: app,
    getPhoneNumber: false,
    skipUserInfoOauth: true,
    staticResPath: cf.config.staticResPath,
    userImagePath: cf.config.userImagePath,
    shareMask: false,
    card_detail_noread: 0,
    card: {
    },
    address: '',
    isLocation: false,
    isThumbs: false,
    isSales: false,
    adInfo: { show: false },
    isOpen: false,//播放开关
    starttime: '00:00', //正在播放时长
    duration: '00:00', //总时长,
    isFirstIn: true,
    memberCount: 0,
    reGoodList: [],
    cardStyleId: 0
  },
  
  //开始播放
  audioPlay: function () {
    var ctx = this;
    util.addBehaviorTrail(ctx.data.eId, 24);
    this.audioCtx.play()
    this.setData({
      isOpen: true
    })
  },

  //暂停播放
  audioPause: function () {
    this.audioCtx.pause()
    this.setData({
      isOpen: false
    })
  },

  //拖动进度条
  sliderChange(e) {
    var offset = parseInt(e.detail.value);
    this.audioCtx.seek(offset);
  },

  //监听播放时长
  updata(e) {
    var that = this;
    var duration = e.detail.duration; //总时长
    var offset = e.detail.currentTime; //当前播放时长
    var currentTime = parseInt(e.detail.currentTime);
    var min = "0" + parseInt(currentTime / 60);
    var max = "0" + parseInt(e.detail.duration / 60);
    var durationmax = parseInt(e.detail.duration)
    var sec = currentTime % 60;
    var sexmax = parseInt(e.detail.duration) % 60;

    if (sec < 10) {
      sec = "0" + sec;
    };
    if (sexmax < 10) {
      sexmax = "0" + sexmax;
    };

    var starttime = min + ':' + sec; /* 00:00 */
    var durationtime = max + ':' + sexmax
    that.setData({
      offset: currentTime,
      starttime: starttime,
      duration: durationtime,
      max: durationmax
    })

    //判断音频播放结束
    if (offset >= duration) {
      that.setData({
        starttime: '00:00', //正在播放时长
        isOpen: false,
        offset: 0
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('????????????????????',options)
    wx.hideShareMenu();
    var ctx = this;
    wx.setNavigationBarTitle({
      title: app.globalData.cardTitle + '预览',
    })
    var emp = wx.getStorageSync("employee");
    ctx.setData({
      eId: emp.id
    });


    app.getUserInfo(this, options, function (userInfo, res) {
      cusmallToken = wx.getStorageSync('cusmallToken');
      var visitCardConfig = wx.getStorageSync("visitCardConfig");
      var companyInfo = wx.getStorageSync('companyInfo');
      ctx.setData({
        companyInfo: wx.getStorageSync('companyInfo'),
        address: companyInfo.location,
        mallEnable: visitCardConfig.mallEnable,
        getPhoneNumber: visitCardConfig.authTelEnable && !wx.getStorageSync('hasGetCustomMobile')
      });
      var curUserIsEmp = wx.getStorageSync('employee');

        ctx.queryDetail();
        ctx.getMemberCountByEid();
        //获取推荐商品/产品
        ctx.fetchReGoodsList();
      //2 名片页底部广告
      // ctx.getAdInfo(wx.getStorageSync('advertConfig'), 2);
    });
    //使用wx.createAudioContext 获取 audio
    this.audioCtx = wx.createAudioContext('myAudio')
  },
  queryDetail() {//查询当前 卡片 的员工信息
    var ctx = this;
    wx.showLoading({
      title: '加载中',
    });
    wx.request({
      url: cf.config.pageDomain + '/applet/mobile/visitcard/employee/getEmployeeInfo',
      data: {
        cusmallToken: cusmallToken,
        eid: ctx.data.eId
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && data.ret == 0 && data.model.employee) {
          data.model.employee.showPic = data.model.employee.showPic && data.model.employee.showPic.split(",") || [];
          let tel = data.model.employee.phone;
          let telSplit;
          if (tel) {
            telSplit = tel.substring(0, 3) + " " + tel.substring(3, 7) + " " + tel.substring(7, 12)
          }
          data.model.employee.telSplit = telSplit;
          if (data.model.employee.personalProfile) {
            var profilestr = data.model.employee.personalProfile.replace(/\r\n/g, '<br/>').replace(/\n/g, '<br/>').replace(/\s/g, ' '); ctx.setData({
              test: profilestr
            })
          }


          if (data.model.employee.extend) {
            data.model.employee.extend = JSON.parse(data.model.employee.extend)
            var resData = data.model.employee.extend;

            if (resData.region) {
              ctx.setData({
                address: resData.region.split(',').join("") + resData.address
              });
            }

            if (resData.locationInfo && resData.locationInfo.latitude) {
              ctx.setData({
                isLocation: true
              });
            }


            ctx.setData({
              empExtend: resData
            });
          }
          ctx.setData({
            card: data.model.employee,
            isThumbs: data.model.isThumbs == undefined ? false : data.model.isThumbs,
            cardStyleId: data.model.employee.cardStyleId == undefined ? 0 : data.model.employee.cardStyleId
          })
          app.globalData.card = data.model.employee;
        } else {
          setTimeout(function () {
            ctx._goback();
          }, 1000)
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    })
  },
  /**
   * 查找当前 名片的客户数
   */
  getMemberCountByEid() {
    var ctx = this;
    wx.request({
      url: cf.config.pageDomain + '/applet/mobile/visitcard/memberrelation/getMemberCountByEid',
      data: {
        cusmallToken: cusmallToken,
        employeeId: ctx.data.eId
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && data.ret == 0) {
          ctx.setData({
            memberCount: data.model.count,
            mHeadImgs: data.model.headImgs
          })
        } else {

        }
      },
      complete: function () {
      }
    })
  },
  /**
   * 查询推荐商品/产品
   */
  fetchReGoodsList() {
    var ctx = this;
    var reqUrl = "";
    var submitData = {
      cusmallToken: cusmallToken,
      eid: ctx.data.eId,
      start: 0,
      limit: 3
    };
    var key = "";
    if (ctx.data.mallEnable) {//商城
      reqUrl = "/applet/mobile/visitcard/goodsNew/findRecommendedGoodsByEid";
    } else {//产品
      reqUrl = "/applet/mobile/visitcard/goods/findGoodsRecommendedByEid";
    }
    wx.request({
      url: cf.config.pageDomain + reqUrl,
      data: submitData,
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && data.ret == 0) {
          var reGoodList = data.model.list;

          for (let item of reGoodList) {
            item.thumbnail = item.thumbnail || (item.pics && item.pics.split(",")[0]);// 商城商品 没有pics 属性
          }

          ctx.setData({
            reGoodList: reGoodList
          });
        } else {
          wx.showToast({
            title: data.msg,
            icon: "none"
          })
        }
      },
      complete: function () {
      }
    })
  },
  viewImg: function (e) { // 预览图片
    var ctx = this;
    var idx = e.currentTarget.dataset.id;
    var absoultPathPic = [];
    for (var i = 0; i < ctx.data.card.showPic.length; i++) {
      absoultPathPic.push(ctx.data.userImagePath + ctx.data.card.showPic[i]);
    }
    wx.previewImage({
      current: absoultPathPic[idx],
      urls: absoultPathPic
    })
  },
  toPlayVideo(e) {
    var ctx = this;
    wx.navigateTo({
      url: '/pages/single_video/video_play?vUrl=' + ctx.data.card.videoUrl,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角
   */
  onShareAppMessage: function () {
    let ctx = this;
    let title;
    if (null == ctx.data.card.shareSpeech) {
    	title = "你好，我是"+ctx.data.companyInfo.shortName+'的'+ctx.data.card.name;
    } else {
    	title = ctx.data.card.shareSpeech;
    }
    let path = "/pages/mycard/card?eId=" + ctx.data.eId + "&source=1"
    let shareObj = {
		title: title,
		path: path,
		success: function (res) {
			util.addBehaviorTrail(eId, 3);
		},
		fail: function (res) {
		}
    };
    return shareObj;
  }
}))